<template>
  <div class="my-container d-flex flex-column p-3">
    <div class="shadow rounded-lg d-flex flex-column">
      <div class="d-flex flex-column">
        <div class="p-3">
          <div class="d-flex flex-row flex-wrap ">
            <div class="col-1 col-center">
              <el-button type="success" @click="returnUrl()">返回</el-button>
            </div>
            <div class="col-13 col-center">
              <span class="font-weight-bold">设备名称：</span>
              <span>{{ tabList.deviceName }}</span>
            </div>
            <div class="col-13 col-center">
              <span class="font-weight-bold">设备编码：</span>
              <span>{{ tabList.deviceCode }}</span>
            </div>
            <div class="col-13 col-center">
              <span class="font-weight-bold">设备描述：</span>
              <span>{{ tabList.deviceDes }}</span>
            </div>
            <div class="col-13 col-center">
              <span class="font-weight-bold">创建时间：</span>
              <span>{{ tabList.createTime }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col shadow rounded-lg mt-3 d-flex flex-column">
      <el-tabs v-model="tabIndex" type="card" @tab-click="handleClick">
        <el-tab-pane label="设备模型参数" name="0"></el-tab-pane>
        <el-tab-pane label="配置设备基础信息" name="1"></el-tab-pane>
        <el-tab-pane label="配置设备自定义参数" name="2"></el-tab-pane>
      </el-tabs>

      <div class="p-3 d-flex flex-column col over-auto" v-if="tabIndex == 0">

        <el-table height="100%" border :data="deviceModelTable" ref="tableRef">
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column prop="parameterName" label="参数名称" align="center" />
          <el-table-column prop="parameterCode" label="参数代码" align="center" />
          <el-table-column prop="parameterType" label="参数类型解析" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.parameterType == 0"> 数值参数</span>
              <span v-if="scope.row.parameterType == 1"> 状态参数</span>
              <span v-if="scope.row.parameterType == 2"> 枚举参数</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="roleName" label="操作" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="primary">查看</el-button>
            </template>
          </el-table-column> -->
        </el-table>
        <pagination class="pagination" :total="count" :page.sync="deviceModel.pageIndex"
          :limit.sync="deviceModel.pageSize" @pagination="pagination" />
      </div>

      <div class="p-3 d-flex flex-column col over-auto" v-if="tabIndex == 1">
        <div class="   col over-auto">
          <el-table height="100%" border :data="deviceInfoTable" ref="tableRef">
            <el-table-column type="index" label="序号" align="center" width="300"></el-table-column>
            <el-table-column prop="label" label="配置对象" align="center">
            </el-table-column>
            <el-table-column prop="roleName" label="配置内容" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.type == 0">
                  <el-select size="mini" v-model="isForceData.forces" placeholder="请选择">
                    <el-option v-for="item in isForceShowType" :key="item.key" :label="item.label" :value="item.key">
                    </el-option>
                  </el-select>
                </span>
                <span v-if="scope.row.type == 1">
                  <el-input size="mini" v-model="isForceData.deviceOfRegionSysName"
                    style="width: 200px; margin-right: 10px;" placeholder="请选择" />
                  <el-button type="primary" size="mini" @click="handleTree">
                    选择</el-button>
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="d-flex mt-3 justify-content-center">
          <el-button type="primary" @click="handleSaveInfo">保存</el-button>
        </div>
      </div>

      <div class="p-3 d-flex flex-column col over-auto" v-if="tabIndex == 2">
        <div class="d-flex mb-3 justify-content-end">
          <el-button type="primary" icon="el-icon-plus" @click="handleAddCustom(0, '新增数值型')">新增数值型</el-button>
          <el-button type="primary" icon="el-icon-plus" @click="handleAddCustom(1, '新增布尔型')">新增布尔型</el-button>
        </div>
        <div class="   col over-auto">
          <el-table height="calc(100% - 70px)" border :data="customTable" ref="tableRef">
            <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
            <el-table-column prop="parameterName" label="系统定义参数名称" align="center" />
            <el-table-column prop="parameterCode" label="系统定义参数代码" align="center" />
            <el-table-column prop="parameterType" label="系统定义参数类型" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.parameterType == 0 ? '数值参数' : '状态参数' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="roleName" label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="primary" @click="customParamsUpdata(scope.row)" size="mini">编辑</el-button>
                <el-button type="danger" @click="removeDeviceOwnerPar(scope.row)" size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination class="pagination" :total="customParamsCount" :page.sync="customParams.pageIndex"
            :limit.sync="customParams.pageSize" @pagination="customPagination" />
        </div>
      </div>
    </div>

    <yc-dialog ref="dataDialog" :centerTitle="customTitle" :dialogTitle="customTitle">
      <template #content>
        <el-form ref="dataDialogForm" :model="dataForm" label-width="120px">
          <el-form-item label="自定义参数名称" prop="userName">
            <el-input v-model="dataForm.parameterName" placeholder="请输入" />
          </el-form-item>
          <el-form-item v-if="customsAddType == 0" label="自定义参数单位" prop="unit">
            <el-input v-model="dataForm.unit" placeholder="请输入" />
          </el-form-item>
          <el-form-item v-if="customsAddType == 1" label="结果值TRUE(0)" prop="userName">
            <el-input v-model="dataForm.parameterZeroValue" placeholder="请输入" />
          </el-form-item>
          <el-form-item v-if="customsAddType == 1" label="结果值FALSE(1)" prop="userName">
            <el-input v-model="dataForm.parameterOneValue" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="自定义参数逻辑" prop="userName">
            <div>
              <el-tag type="info" effect="plain" :key="index" closable class="mr-3" @close="delTag(index)"
                v-for="(item, index) in tagList">{{ item }}</el-tag>
              <el-tag type="primary" effect="dark" @click="showTag = true"><i class="el-icon-plus"></i></el-tag>
            </div>
          </el-form-item>
          <div class="d-flex " style="height: 300px;" v-if="showTag">
            <div class="shadow rounded-lg mr-4 p-3" style="width: 250px;">
              <div class="d-flex justify-content-between py-2 pointer" v-for="(item, index) in tagSelectList" :key="index"
                @click="tagSelectIndex = index">
                <div :class="tagSelectIndex == index ? 'text-primary' : ''">{{ item }}</div>
                <i class="el-icon-arrow-right text-primary" v-if="tagSelectIndex == index"></i>
              </div>
            </div>

            <div class="shadow rounded-lg col p-3">
              <div class=" mt-3" v-if="tagSelectIndex == 0">
                <el-button size="mini" v-for="(item, index) in modelListParams" :key="index"
                  @click="pushString(0, item.name, item.code)" class="ml-0 mr-3 mb-3" style="width: 120px;">{{ item.name
                  }}</el-button>
              </div>
              <div class=" mt-3" v-if="tagSelectIndex == 1">
                <el-button size="mini" v-for="(item, index) in symbolList" :key="index" @click="pushString(1, item)"
                  class="ml-0 mr-3 mb-3" style="width: 120px;">{{ item }}</el-button>

              </div>
              <div class=" mt-3" v-if="tagSelectIndex == 2">
                <el-input size="mini" type="textarea" placeholder="请输入" v-model="tagInput"
                  @blur="pushString(2, tagInput)"></el-input>
              </div>
            </div>
            <div class="position-relative">
              <div class="position-absolute" style="right: 10px;top: 10px;">
                <i class="el-icon-close font-weight-bold font-20" @click="showTag = false"></i>
              </div>
            </div>
          </div>
        </el-form>

      </template>
      <template #footer>
        <el-button type="primary" @click="dataDialogSave">确定</el-button>
        <el-button @click="$refs.dataDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>

    <!-- 区域位置 -->
    <yc-dialog ref="regionDialog" centerTitle="选择" dialogTitle="区域位置">
      <template #content>
        <el-tree ref="tree1" :default-checked-keys="[regionTreeAction.deviceOfRegion]" node-key="zoneCode"
          :data="regionTreeData" show-checkbox check-strictly :props="defaultProps" check-on-click-node
          :expand-on-click-node="false" highlight-current @check="deptNodeClick" />
      </template>
      <template #footer>
        <el-button type="primary" @click="regionTreeSave()">确定</el-button>
        <el-button @click="$refs.regionDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>
  </div>
</template>

<script>
import ycDialog from "@/components/pageDialog"
import {
  queryOneDeviceSedModelParameter,
  queryDeviceOwnerParPage,
  queryParametersPageByDevice,
  queryOneDevice,
  queryParamForOwnParList,
  insertDeviceOwnerPar,
  queryDeviceOwnerPar,
  updateDeviceOwnerPar,
  updateOneDevice,
  deleteDeviceOwnerPar
} from "@/api/settingManagement/devicesSetting"
import { selectZonePage } from "@/api/regionalSettings"

export default {
  components: {
    ycDialog
  },
  props: {
  },
  data () {
    return {
      activeName: 'first',
      showTag: false,
      modelList: [{
        name: '参数名称',
        list: ['A相电压', 'B相电压', 'C相电压',]
      }, {
        name: '参数代码',
        list: ['UA', 'UB', 'UC',]
      }],
      tagInput: '',
      symbolList: ['(', ')', '+', '-', '*', '/', '>', '<', '==', '&&', '||'],
      modelListParams: [],
      tagSelectList: ['设备模型参数', '符号', '输入框'],
      tagSelectIndex: 0,
      tagList: [], //自定义参数标签
      dataForm: {
        parameterName: '',
        parameterZeroValue: '',
        parameterOneValue: '',
        unit: ''
      },
      select: '',
      tab: ['设备模型参数', '配置设备基础信息', '配置设备自定义参数'],
      tabIndex: 0,
      modelOptions: [{
        label: "正常",
        value: 1
      },],
      modelForm: {},
      tabList: {},
      detailId: '',

      count: 0,
      customParamsCount: 0,
      deviceModel: {
        pageIndex: 1,
        pageSize: 20,
      },
      customParams: {
        pageIndex: 1,
        pageSize: 20,
      },
      deviceModelTable: [],
      deviceInfoTable: [
        {
          label: '升级方式',
          type: 0
        },
        {
          label: '设备区域',
          type: 1
        }
      ],
      isForceData: {
        forces: '',
        deviceOfRegionSysName: '',

      },
      isForceShowType: [],
      regionTreeData: [{
        id: 1,
        label: '一级 2',
        children: [{
          id: 3,
          label: '二级 2-1',
          children: [{
            id: 4,
            label: '三级 3-1-1'
          }, {
            id: 5,
            label: '三级 3-1-2',
          }]
        }, {
          id: 2,
          label: '二级 2-2',
          children: [{
            id: 6,
            label: '三级 3-2-1'
          }, {
            id: 7,
            label: '三级 3-2-2',
          }]
        }]
      }],
      defaultProps: {
        children: 'bZoneList',
        label: 'zoneName'
      },
      regionTreeAction: {
        deviceOfRegionName: '',
        deviceOfRegion: ''
      },
      customTable: [],
      customTitle: '',
      customsAddType: '',
      customDialogType: '',
      mapString: [],
      parameterOwnerSysCode: ''
    }
  },
  created () {

  },
  mounted () {
    this.deviceCode = this.$route.query.deviceCode
    this.tabList = this.$route.query
    this.queryParametersPageByDevice()
  },
  methods: {
    returnUrl () {
      this.$router.go(-1)
    },
    handleClick (tab, event) {
      switch (tab.index) {
        case '0':
          this.queryParametersPageByDevice()
          break
        case '1':
          this.getQueryOneDevice()

          break
        case '2':
          this.queryDeviceOwnerParPage()
          break

        default:
          break
      }
    },
    delTag (index) {
      this.tagList.splice(index, 1)
      this.mapString.splice(index, 1)
    },

    queryParametersPageByDevice () {
      queryParametersPageByDevice({
        deviceCode: this.deviceCode,
        ...this.deviceModel
      }).then(res => {
        if (res.status == 200) {
          this.count = res.object.count
          this.deviceModelTable = res.object.data
        }
      })
    },
    async getQueryOneDevice () {
      let isForceType = [
        {
          label: '手动升级',
          key: '0',
        },
        {
          label: '自动升级',
          key: '1',
        },
        {
          label: '定时升级',
          key: '2',
        },
        {
          label: '无法升级',
          key: '3',
        }
      ]
      const res = await queryOneDevice({ deviceCode: this.deviceCode, })
      if (res.status == 200) {
        this.isForceData = res.object
        let type = JSON.parse(res.object.isForce)
        this.isForceShowType = isForceType.filter(item => type.indexOf(item.key) > -1)
        console.log(this.isForceShowType)
        this.regionTreeAction.deviceOfRegion = this.isForceData.deviceOfRegion
      }
    },
    handleTree () {
      this.getZone()
      this.$refs.regionDialog.dialogVisible = true
    },
    deptNodeClick (data) {
      this.$refs.tree1.setCheckedNodes([{
        zoneCode: data.zoneCode,
        zoneName: data.zoneName
      }])
      this.regionTreeAction.deviceOfRegion = data.zoneCode
      this.regionTreeAction.deviceOfRegionName = data.zoneName
    },
    regionTreeSave () {
      this.isForceData.deviceOfRegionSysName = this.regionTreeAction.deviceOfRegionName
      this.$refs.regionDialog.dialogVisible = false
    },
    pagination (pageItem) {
      // pageItem.page, pageItem.limit
      this.deviceModel.pageIndex = pageItem.page
      this.deviceModel.pageSize = pageItem.limit
      this.queryParametersPageByDevice()
    },
    handleAddCustom (type, text) {
      this.dataForm.parameterName = ''
      this.dataForm.parameterZeroValue = ''
      this.dataForm.parameterOneValue = ''
      this.dataForm.unit = ''
      this.tagInput = ''
      this.tagList = []
      this.mapString = []

      this.customDialogType = 'add'
      this.handleCustom(type, text)
    },

    handleCustom (type, text) {

      this.customsAddType = type
      this.customTitle = text
      this.$refs.dataDialog.dialogVisible = true
      this.queryParamForOwnParList()
    },

    async queryDeviceOwnerParPage () {
      const res = await queryDeviceOwnerParPage({
        deviceCode: this.deviceCode,
        ...this.customParams
      })
      if (res.status == 200) {
        this.customTable = res.object.data
      }
    },
    customPagination (pageItem) {
      this.customParams.pageIndex = pageItem.page
      this.customParams.pageSize = pageItem.limit
      this.queryDeviceOwnerParPage()
    },

    async queryParamForOwnParList () {
      const res = await queryParamForOwnParList({ deviceCode: this.deviceCode })
      if (res.status == 200) {
        this.modelListParams = res.object
      }
    },
    //保存数值类型
    async dataDialogSave () {
      if (this.customDialogType == 'add') {
        const data = {
          deviceCode: this.deviceCode,
          parameterType: this.customsAddType,
          messages: JSON.stringify(this.mapString),
          ...this.dataForm
        }
        const res = await insertDeviceOwnerPar(data)
        if (res.status == 200) {
          this.$message({
            type: "success",
            message: res.message,
          })
          this.$refs.dataDialog.dialogVisible = false
          this.queryDeviceOwnerParPage()
        }
      } else {
        const data = {
          deviceCode: this.deviceCode,
          parameterType: this.customsAddType,
          parameterOwnerSysCode: this.parameterOwnerSysCode,
          messages: JSON.stringify(this.mapString),
          ...this.dataForm
        }
        const res = await updateDeviceOwnerPar(data)
        if (res.status == 200) {
          this.$message({
            type: "success",
            message: res.message,
          })
          this.$refs.dataDialog.dialogVisible = false
          this.queryDeviceOwnerParPage()
        }
      }

    },

    pushString (type, val, code) {
      this.tagList.push(val)
      this.mapString.push({
        type: type,
        seqValue: code ? code : val,
        seqValueName: val,
      })
    },
    async customParamsUpdata (row) {
      this.parameterOwnerSysCode = row.parameterOwnerSysCode
      const res = await queryDeviceOwnerPar({ parameterOwnerSysCode: this.parameterOwnerSysCode })
      if (res.status == 200) {
        this.tagList = []
        this.mapString = []
        this.tagInput = ''
        this.customDialogType = 'updata'
        this.dataForm.parameterName = res.object.parameterName
        this.dataForm.parameterZeroValue = res.object.parameterZeroValue
        this.dataForm.parameterOneValue = res.object.parameterOneValue
        res.object.parsingList.forEach(element => {
          this.tagList.push(element.seqValueName)
          this.mapString.push({
            type: element.type,
            seqValue: element.seqValue,
            seqValueName: element.seqValue,
          })
        })
        this.handleCustom(res.object.parameterType, res.object.parameterType == 0 ? '编辑数值型' : '编辑布尔型')
        // this.queryDeviceOwnerParPage()
      }
    },
    //----------------2
    //查询区域
    async getZone () {
      const res = await selectZonePage()
      if (res.status == '200') {
        this.regionTreeData = res.object
      }
    },
    async handleSaveInfo () {
      const param = {
        deviceCode: this.deviceCode,
        forces: this.isForceData.forces,
        ...this.regionTreeAction
      }
      const res = await updateOneDevice(param)
      if (res.status == '200') {
        this.$message({
          type: "success",
          message: res.message,
        })
        this.getQueryOneDevice()
      }
    },
    //----------------3
    async removeDeviceOwnerPar (row) {
      const res = await deleteDeviceOwnerPar({ parameterOwnerSysCode: row.parameterOwnerSysCode })
      if (res.status == '200') {
        this.$message({
          type: "success",
          message: res.message,
        })
        this.queryDeviceOwnerParPage()
      }
    }
  }
}
</script>

<style scoped lang="scss">
.tab-item {
  width: 20%;
}

.pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
